<?php

namespace app\jigou\controller\qingdongams\customer;

use addons\qingdongams\model\BusinessStatus;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\Field;
use addons\qingdongams\model\File;
use addons\qingdongams\model\BusinessProduct;
use addons\qingdongams\model\FormField;
use addons\qingdongams\model\Product;
use addons\qingdongams\model\Staff;
use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\BusinessOther;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\Contract;
use addons\qingdongams\model\Record;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use think\Db;
use think\Exception;
use think\Session;


/**
 * 商机管理
 * @icon fa fa-handshake-o
 */
class Business extends Base
{
    protected $relationSearch = true;
    /**
     * @var \addons\qingdongams\model\Business
     */
    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \addons\qingdongams\model\Business;
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //0:全部 1：我负责的 2：下属负责的 3：今日待跟进 4:今日已跟进 5:从未跟进的
            $type = input('type', 0);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            switch ($type) {
                case 1:
                    $staff = Staff::info();
                    $wheres['business.owner_staff_id'] = $staff->id;
                    break;
                case 2:
                    $wheres['business.owner_staff_id'] = array('in', Staff::getLowerStaffId());
                    break;
                case 3:
                    $start = date('Y-m-d 00:00:00');
                    $end = date('Y-m-d 23:59:59');
                    $record = Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select();
                    $relationId = [];
                    foreach ($record as $k => $v) {
//                        $whereRe['id'] = array('gt', $v['id']);
                        $whereRe['relation_id'] = $v['relation_id'];
                        $recordData = Record::where($whereRe)->count();
                        if ($recordData == 0) {
                            $relationId[] = $v['relation_id'];
                        }

                    }
                    $wheres['business.id'] = array('in', $relationId);
                    $staff = Staff::info();
                    $wheres['business.owner_staff_id'] = $staff->id;
                    break;
                case 4:
                    $start = date('Y-m-d 00:00:00');
                    $end = date('Y-m-d 23:59:59');
                    $record = Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', strtotime($start)), array('elt', strtotime($end)))))->field("id,relation_id")->select();
                    $relationId = [];
                    foreach ($record as $k => $v) {
                        $whereRe['id'] = array('gt', $v['id']);
                        $whereRe['relation_id'] = $v['relation_id'];
                        $recordData = Record::where($whereRe)->count();
                        if ($recordData >= 1) {
                            $relationId[] = $v['relation_id'];
                        }

                    }
                    $wheres['business.id'] = array('in', $relationId);
                    $staff = Staff::info();
                    $wheres['business.owner_staff_id'] = $staff->id;
                    break;
                case 5:
                    $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
                    $wheres['business.id'] = array('not in', $record);
                    $staff = Staff::info();
                    $wheres['business.owner_staff_id'] = $staff->id;
                    break;
                default:
                    $wheres['business.owner_staff_id'] = array('in', Staff::getMyStaffIds());
                    break;

            }
            $ids = [];
            $group_id = input('group_id');
            $staff_id = input('staff_id');
            if ($group_id) {//角色组
                $ids = Staff::getGroupStaffIds($group_id);
            }
            if ($staff_id) {
                $ids = $staff_id;
            }
            if ($group_id || $staff_id) {
                $wheres['business.owner_staff_id'] = ['in', $ids];
            }
            $list = $this->model->alias("business")->where($where)
                ->where($wheres)
                ->with([
                    'customer',
                    'ownerStaff',
                    'product'
                ])->join("qingdongams_customer customer1", "business.customer_id=customer1.id", "left")->where("customer1.customer_type", "家长")->where("customer1.jigou_id", Session::get("jigou_id"))->where("customer1.jigou_id", Session::get("jigou_id"))->field("business.*")->order($sort, $order)->paginate($limit);
            foreach ($list as $k => $v) {
                $types = BusinessStatus::where(array('business_id' => $v['id']))->order('id desc')->value('type');
                $list[$k]['type'] = $types ? (int)$types : 0;
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $field = FormField::getFields(FormField::BUSINESS_TYPE);
        $this->assignconfig('fields', $field);
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);
                $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params);
                if ($result !== true) {
                    $this->error($result);
                }
                $result = false;
                Db::startTrans();
                try {

                    $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params);

                    if ($params['product']) {
                        $params['product'] = json_decode($params['product'], true);
                    }
                    $result = $this->model::createBusiness($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $customer_id = input('customer_id');
        $this->assign('customer_id', $customer_id);
        $this->assign('customer', Customer::get($customer_id));
        $this->assign('customer_type', "家长");


        $this->assign('staffs', Staff::allList());
        $this->assign('form_data', Form::getDataValue('business'));
        return $this->view->fetch();
    }

    /**
     * 修改
     */
    public function edit($ids = null)
    {
        $map['id'] = $ids;
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $params = $this->preExcludeFields($params);

            $result = FormField::checkFields(FormField::BUSINESS_TYPE, $params, $ids);
            if ($result !== true) {
                $this->error($result);
            }
            Db::startTrans();
            try {
                $params = Form::updateFormParams(Form::BUSINESS_TYPE, $params);
                $params['id'] = $ids;
                $result = $this->model::updateBusiness($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        $row = $this->model->where($map)->with(['customer'])->find();
        $product = BusinessProduct::where(['business_id' => $ids])->with(['productinfo'])->select();
        foreach ($product as $k => $v) {
            if ($v['productinfo']) {
                $v['product_name'] = $v['productinfo']['name'];
                $v['cost_price'] = $v['productinfo']['cost_price'];
                $v['type'] = $v['productinfo']['type'];
                if ($v['productinfo']['goods']) {
                    $v['goods_name'] = $v['productinfo']['goods']['name'];
                }
            }
            $product[$k] = $v;
        }
        $row['product'] = json_encode($product);
        $row = $row->toArray();
        $row = BusinessOther::getOther($row);

        $this->view->assign("row", $row);
        $this->assign('customers', Customer::getList());
        $this->assign('form_data', Form::getDataValue('business', $row));

        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->where(['id' => $ids])->with([
            'customer',
            'ownerStaff'
        ])->find();
        if (empty($row)) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $row = BusinessOther::getOther($row);

        //跟进记录
        $this->assign('records', Record::getList(Record::CONTRACT_TYPE, $ids));
        $type = BusinessStatus::where(array('business_id' => $ids))->order('id desc')->value('type');
        $row['type'] = $type ? (int)$type : 0;
        $this->assign('row', $row);
        $this->assign('ids', $ids);
        $this->assign('form_data', Form::getDataValue('business', $row));
        $this->assignconfig("idinfo", ['id' => $ids]);
        return $this->view->fetch();
    }

    /**
     * 添加跟进
     */
    public function record($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $params['relation_type'] = 5;
            $params['relation_id'] = $ids;

            if (!empty($params['files'])) {
                $params['files'] = File::getId($params['files']);
            }
            $reminds_id = $this->request->post('reminds_id/a');
            $params['reminds_id']='';
            if($reminds_id){
                $params['reminds_id'] = implode(',',$reminds_id);
            }
            Db::startTrans();
            try {

                $result = Record::createRecord($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result) {
                $this->success('创建跟进记录成功');
            }
            $this->error('创建失败');
        }

        $staff = Staff::where(['status'=>1])->column('name', 'id');
        $follow = Field::getField('商机阶段');
        $this->assign('follow', $follow);
        $this->assign('ids', $ids);
        $this->assign('staff', $staff);
        return $this->view->fetch();
    }

    /**
     * 批量转移商机
     */
    public function batch_change($ids = null)
    {
        $ids = json_decode($ids, true);
        $ids = $this->model->where([
            'id' => ['in', $ids]
        ])->column('id');
        if (empty($ids)) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model::batchTransfer($ids, $params['owner_staff_id']);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $staffs = Staff::getList();
        $this->assign('staffs', $staffs);
        $this->assign('ids', json_encode($ids));

        return $this->view->fetch();
    }

    /**
     * 产品信息
     */
    public function product()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $business_id = input('business_id');
            $wheres['business_product.business_id'] = $business_id;
            $list = BusinessProduct::where($where)->where($wheres)->with(['product'])->order($sort, $order)->paginate($limit);
            foreach ($list as $k => $v) {
                if (!$v['product']['id']) {
                    unset($list[$k]);
                }
            }
            $row = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 获取相关订单
     */
    public function get_contract()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $business_id = input('business_id');
        $wheres['business_id'] = $business_id;
        $list = Contract::where([
            'business_id' => $business_id,
        ])->with('customer')->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }

    /**
     * 删除商机
     */
    public function delete($ids = null)
    {
        if (!$ids) {
            $this->error('参数不正确');
        }
        $data = $this->model->where([
            'id' => $ids
        ])->column('id');
        if (empty($data)) {
            $this->error('商机不存在');
        }
        $result = $this->model->where(array('id' => $ids))->update(array('updatetime' => time(), 'deletetime' => time()));
        if (!$result) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }

    /**
     * 推进商机
     */
    public function batch_status($ids = null)
    {
        $ids = $this->model->where([
            'id' => $ids
        ])->value('id');
        if (empty($ids)) {
            $this->error('商机不存在');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if (!empty($params['file'])) {
                    $params['file'] = File::getId($params['file']);
                }
                $result = false;
                Db::startTrans();
                try {
                    $params['id'] = $ids;
                    $result = $this->model::batchStatus($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error('推进失败');
                }
            }
            $this->error('推进失败');
        }


        return $this->view->fetch();
    }

    /**
     * 获取推进商机
     */
    public function get_business_status()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $business_id = input('business_id');
        $wheres['business_id'] = $business_id;
        $list = BusinessStatus::where([
            'business_id' => $business_id,
        ])->order('id desc')->paginate($limit);
        foreach ($list as $k => $v) {
            if ($v['file']) {
                $list[$k]['file'] = File::where(array('id' => ['in', $v['file']]))->select();
            }

        }
        $result = array("total" => $list->total(), "rows" => $list->items());

        return json($result);
    }


    /**
     * 导入客户
     * @return string|void
     */
    public function import()
    {
        set_time_limit(0);
        if ($this->request->isPost()) {

            $file = $this->request->request('file');
            $staff_id = $this->request->request('staff_id', 0);
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . 'public' . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表

            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            //开始读取数据
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[$currentRow][] = $val;
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? '' : trim($val);
                }
            }
            if (!isset($fields[1])) {
                $this->error('导入文件第一行没有数据');
            }
            $lastid = $this->model->order('id desc')->value('id');

            $lastid = $lastid + 5;//防止重复

            $customerRow = [];
            $errorInfo = [];

            $customerNames = Customer::where([])->column('id,owner_staff_id', 'name');

            $fieldnames = FormField::where(['types' => FormField::BUSINESS_TYPE])->column('field', 'name');
            $fn = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                foreach ($values as $l) {
                    $fn[] = $fieldnames[$l] ?? '';
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? NULL : trim($val);
                }
                $lastid++;
                $addBusiness = ['id' => $lastid];
                $customer = isset($customerNames[$values[0]]) ? $customerNames[$values[0]] : 0;
                if (empty($customer)) {
                    $errorInfo[] = "第{$currentRow}行，客户名称不存在;";
                    continue;
                }
                $addBusiness['customer_id'] = $customer['id'];
                $addBusiness['owner_staff_id'] = $customer['owner_staff_id'];
                foreach ($values as $kv => $value) {
                    if (!isset($fn[$kv]) || empty($fn[$kv])) {
                        continue;
                    }
                    $addBusiness[$fn[$kv]] = $value;
                }

                if (empty($addBusiness['name'])) {
                    $errorInfo[] = "第{$currentRow}行，商机名称不能为空;";
                    continue;
                }
                $customerRow[] = $addBusiness;
            }
            if (!empty($errorInfo)) {
                $this->error(implode(',', $errorInfo));
            }
            Db::startTrans();
            try {
                $this->model::importBusiness($customerRow);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('导入成功');
        }
        $this->assign('staffs', Staff::getList());
        return $this->view->fetch();
    }

    /**
     * 模板
     */
    public function template()
    {
        $title = ['客户名称'];
        $dataValue = Form::getDataValue(Form::BUSINESS_TYPE);

        foreach ($dataValue as $val) {
            $title[] = $val['config']['label'];
        }

        $file = export_excel($title, [], '商机');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $file['fileName']);
        header('Cache-Control: max-age=0');

        $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('导出文件'); //设置标题
        $obj->setActiveSheetIndex(0);
        $obj->getActiveSheet()->setTitle('导出文件');
        /* 循环读取每个单元格的数据 */
        $a = 'A';
        $currentSheet = $obj->getActiveSheet();
        foreach ($title as $key => $value) {
            //读取工作表1
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
            //这里是设置单元格的内容
            $currentSheet->getCell($a . '1')->setValue($value);
            $a++;
        }

        $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);

        $PHPWriter->save('php://output');
    }

    /**
     * 导出信息
     */
    public function export()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $ids = input('ids');
        $isall = input('isall', 1);
        $wheres = array();
        //导出其中几条
        if (isset($ids) && $ids) {
            $wheres['id'] = array('in', $ids);
        }
        //导出全部
        if ($isall == 3) {
            unset($wheres['id']);
        }
        //0:全部 1：我负责的 2：下属负责的 3：今日待跟进 4:今日已跟进 5:从未跟进的
        $type = input('type', 0);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $staff = Staff::info();
        $staff_id = $staff->id;
        switch ($type) {
            case 1:
                $wheres['owner_staff_id'] = $staff_id;
                break;
            case 2:
                $wheres['owner_staff_id'] = array('in', Staff::getLowerStaffId());
                break;
            case 3:
                $start = date('Y-m-d 00:00:00');
                $end = date('Y-m-d 23:59:59');
                $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
                $relationId = [];
                foreach ($record as $k => $v) {
                    $whereRe['id'] = array('gt', $v['id']);
                    $whereRe['relation_id'] = $v['relation_id'];
                    $recordData = Record::where($whereRe)->count();
                    if ($recordData == 0) {
                        $relationId[] = $v['relation_id'];
                    }

                }
                $wheres['id'] = array('in', $relationId);
                $staff = Staff::info();
                $wheres['owner_staff_id'] = $staff->id;
                break;
            case 4:
                $start = date('Y-m-d 00:00:00');
                $end = date('Y-m-d 23:59:59');
                $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array(array('egt', $start), array('elt', $end))))->field("id,relation_id")->select())->toArray();
                $relationId = [];
                foreach ($record as $k => $v) {
                    $whereRe['id'] = array('gt', $v['id']);
                    $whereRe['relation_id'] = $v['relation_id'];
                    $recordData = Record::where($whereRe)->count();
                    if ($recordData >= 1) {
                        $relationId[] = $v['relation_id'];
                    }

                }
                $wheres['id'] = array('in', $relationId);
                $staff = Staff::info();
                $wheres['owner_staff_id'] = $staff->id;
                break;
            case 5:
                $record = collection(Record::where(array('relation_type' => 5, 'next_time' => array('neq', '')))->column('relation_id'))->toArray();
                $wheres['id'] = array('not in', $record);
                $staff = Staff::info();
                $wheres['owner_staff_id'] = $staff->id;
                break;
            default:
                $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
                break;

        }

        $list = $this->model->with([
            'ownerStaff', 'businessOther', 'customer'
        ])->where($where)->where($wheres)->order($sort, $order)->select();
        $list = collection($list)->toArray();

        if (!$list) {
            $this->error('无导出数据');
        }
        $title = [
            '序号',
            '客户名称',
            '负责人',
            '创建时间',
            '下次联系时间',
        ];

        $dataValue = Form::getDataValue(Form::BUSINESS_TYPE);

        foreach ($dataValue as $val) {
            $title[] = $val['config']['label'];
        }
        foreach ($list as $k => $v) {
            if ($v['business_other']) {//其他客户
                $other = $v['business_other']['otherdata'];
                $other = json_decode($other, true);
                $v = array_merge($v, $other);
            }
            $field = array(
                $v['id'],
                $v['customer']['name'],

                $v['owner_staff']['name'],
                date('Y-m-d H:i:s', $v['createtime']),
                $v['next_time'],
            );
            foreach ($dataValue as $val) {
                if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
                    $field[] = $v[$val['id'] . '_str'] ?? '';
                } else {
                    $field[] = ($v[$val['id']] ?? '');
                }
            }
            $data[] = $field;
        }
        $file = export_excel($title, $data, '商机');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }


    /**
     * 导入产品明细
     * @return string|void
     */
    public function import_product()
    {
        set_time_limit(0);
        if ($this->request->isPost()) {

            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . 'public' . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表

            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            //开始读取数据
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[$currentRow][] = $val;
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? '' : trim($val);
                }
            }
            if (!isset($fields[1])) {
                $this->error('导入文件第一行没有数据');
            }

            $lastid = BusinessProduct::order('id desc')->value('id');

            $lastid = $lastid + 5;//防止重复

            $businessProductRow = [];
            $errorInfo = [];

            $businessName = $this->model::where([])->column('id,name,money', 'name');
            $productName = Product::where([])->column('id,price', 'name');

            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? NULL : trim($val);
                }
                $lastid++;
                $addContractProduct = ['id' => $lastid];
                $business = isset($businessName[$values[0]]) ? $businessName[$values[0]] : 0;
                if (empty($business)) {
                    $errorInfo[] = "第{$currentRow}行，商机名称不存在;";
                    continue;
                }
                $product = isset($productName[$values[1]]) ? $productName[$values[1]] : 0;
                if (empty($product)) {
                    $errorInfo[] = "第{$currentRow}行，产品名称不存在;";
                    continue;
                }
                if (empty($values[2])) {
                    $errorInfo[] = "第{$currentRow}行，产品数量不能为空;";
                    continue;
                }
                if (empty($values[3])) {
                    $errorInfo[] = "第{$currentRow}行，产品售价不能为空;";
                    continue;
                }
                $addContractProduct['business_id'] = $business['id'];
                $addContractProduct['product_id'] = $product['id'];
                $addContractProduct['number'] = $values[2];
                $addContractProduct['price'] = $values[3];
                $businessProductRow[] = $addContractProduct;
            }
            if (!empty($errorInfo)) {
                $this->error(implode(',', $errorInfo));
            }
            Db::startTrans();
            try {
                BusinessProduct::importProduct($businessProductRow);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('导入成功');
        }
        $this->assign('staffs', Staff::getList());
        return $this->view->fetch();
    }

    /**
     * 模板
     */
    public function template_product()
    {
        $title = [
            '商机名称',
            '商品名称',
            '数量',
            '售价',
        ];

        $file = export_excel($title, [], '产品明细');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $file['fileName']);
        header('Cache-Control: max-age=0');

        $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('导出文件'); //设置标题
        $obj->setActiveSheetIndex(0);
        $obj->getActiveSheet()->setTitle('导出文件');
        /* 循环读取每个单元格的数据 */
        $a = 'A';
        $currentSheet = $obj->getActiveSheet();
        foreach ($title as $key => $value) {
            //读取工作表1
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
            //这里是设置单元格的内容
            $currentSheet->getCell($a . '1')->setValue($value);
            $a++;
        }

        $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);

        $PHPWriter->save('php://output');
    }

    /**
     * 导出信息
     */
    public function export_product()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $ids = input('ids');
        $type = input('type');
        $wheres = array();
        //导出其中几条
        if (isset($ids)) {
            $wheres['business_id'] = array('in', $ids);
        }
        //导出全部
        if (isset($type)) {
            if ($type == 3) {
                unset($wheres['business_id']);
            }
        }

        $list = BusinessProduct::where($wheres)->with(['business', 'productinfo'])->select();
        $list = collection($list)->toArray();

        if (!$list) {
            $this->error('无导出数据');
        }
        $title = [
            '序号',
            '商机名称',
            '商品名称',
            '售价',
            '批发价',
            '产品',
            '规格',
            '数量',
        ];

        foreach ($list as $k => $v) {

            $field = array(
                $v['id'],
                $v['business']['name'],
                $v['productinfo']['name'] ?? '',
                $v['price'] ?? '',
                $v['productinfo']['cost_price'] ?? '',
                $v['productinfo']['goods']['name'] ?? '',
                $v['productinfo']['unit'] ?? '',
                $v['number'] ?? '',
            );
            $data[] = $field;
        }
        $file = export_excel($title, $data, '产品明细');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }
}